<?php

namespace app\models;
use yii\db\ActiveRecord;
class User extends ActiveRecord implements \yii\web\IdentityInterface
{
    public $authKey;
    public $accessToken;
    
    const ACCESS_TOKEN_CACHE_PREFIX = 'accessToken_';

    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {        return User::find()->where(['id' => $id])->one();
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        $cacheKey = self::ACCESS_TOKEN_CACHE_PREFIX.$token;
        $userId = \Yii::$app->cache->get($cacheKey);
        if ($userId !== false) {
            return static::findIdentity($userId);
        } else {
            return null;
        }
    }

    /**
     * Finds user by username
     *
     * @param  string      $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::find()->where(['username' => $username])->one();
    }
    
    public function createAccessToken() {
        $key = sprintf('%d%d%d',
            time(),
            $this->id,
            mt_rand(0, 1E6)
        );
        
        $accessToken = md5($key);
        $cacheKey = self::ACCESS_TOKEN_CACHE_PREFIX.$accessToken;
        $id = $this->getId();
        $id = $this->getAttribute('id');
        \Yii::$app->cache->set($cacheKey, $this->id);
        return $accessToken;
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->authKey;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->authKey === $authKey;
    }

    /**
     * Validates password
     *
     * @param  string  $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return \Yii::$app->security->validatePassword($password, $this->password);
    }
}
